﻿<link href="@Url.Content("/content/styles/order.css")" rel="stylesheet" type="text/css" />

<div class="ld-tabs">
    <ul>
        <li class="k-state-active">填写新的 @Invoicing.Web.Management.Common.GetOrderName(ViewBag.Method)</li>
        <li>预订单列表</li>
    </ul>
    <div>
        <div class="k-block form_title">
            <div>
                <b>客户：</b><input id="txtCustomer" data-value="0" style="width: 400px" />
                <b>日期：</b><input id="txtNoteDate" />
            </div>
            <div style="margin-top: 10px;">
                <b>备注：</b><input type="text" class="k-textbox" id="txtDescription" style="width: 90%" />
            </div>
        </div>
        <div id="grid_orders"></div>
        <table class="tbsum">
            <tr>
                <td style="width: 296px"></td>
                <td style="width: 295px;">&nbsp;&nbsp;总金额：<span id="lblSum"></span></td>
                <td>&nbsp;</td>
            </tr>
        </table>
    </div>
    <div>
        <div id="grid_books"></div>
    </div>
</div>


<script class="init">
    var submenu;
    @if (ViewBag.Method == 1)
    {
        <text>submenu = "新采购单";</text>
    }
    else if (ViewBag.Method == 2)
    {
        <text>submenu = "新销售单";</text>
    }
    else if (ViewBag.Method == 3)
    {
        <text>submenu = "采购退货";</text>
    }
    else if (ViewBag.Method == 4)
    {
        <text>submenu = "销售退货";</text>
    }
    LocatedMenu("交易管理", submenu);
    $("#txtNoteDate").kendoDatePicker({
        value: new Date(),
        culture: "zh-CHS",
        format: "yyyy年MM月dd日"
    });

    var allCustomer = Whale.Remote.GetEntity({
        url: "/Members/Customer/Gets",
        parameters: {
            cType: "@(ViewBag.Method % 2 == 0 ? 1 : 2)",
            customerStatus: 1
        }
    });

    $("#txtCustomer").kendoComboBox({
        placeholder: "请选择客户...",
        filter: "contains",
        dataTextField: "SearchLabel",
        template: "#=ComplexName#",
        dataValueField: "ID",
        dataSource: allCustomer,
        select: function (e) {
            var item = this.dataItem(e.item.index());
            $("#txtCustomer").attr("data-value", item.ID);
        },
        change: function (e) {
            var item = this.dataItem();
            if (item != undefined) {
                this.text(item.ComplexName);
            } else {
                var b = true;
                var obj = this;
                $.each(allCustomer, function (i, o) {
                    if (obj.text() == o.ComplexName) {
                        b = false;
                    }
                });
                if (b) {
                    this.text("");
                    $("#txtCustomer").attr("data-value", "0");
                }
            }
        }
    });
</script>

<script class="grid_orders_columns">
    var orderFields = [{
        title: "产品型号",
        field: "Product",
        template: "#=Product.Module#",
        editor: productEditor,
        width: 200
    }, {
        title: "材料",
        field: "Material",
        template: "#=Material.MaterialName#",
        editor: materialEditor,
        width: 120
    }, {
        title: "加工",
        field: "Process",
        template: "#=Process.ProcessName#",
        editor: processEditor,
        width: 100
    }, {
        title: "规格",
        field: "Size",
        template: "#=Size.SizeName#",
        editor: sizeEditor,
        width: 100
    }, {
        title: "数量(只)",
        field: "Quantity",
        editor: quantityEditor,
        width: 100
    }, {
        title: "单价(只)",
        field: "UnitPrice",
        format: "{0:c5}",
        editor: priceEditor,
        width: 100
    }, {
        title: "数量(斤)",
        field: "WeightQuantity",
        editor: quantityEditor,
        width: 100
    }, {
        title: "单价(斤)",
        field: "WeightUnitPrice",
        format: "{0:c2}",
        editor: priceEditor,
        width: 100
    }, {
        title: "金额",
        field: "Money",
        format: "{0:c}",
        width: 100

    }, {
        title: "操作",
        command: [{
            name: "destroy",
            text: "删除"

        }]
    }];

    var allProducts = Whale.Remote.GetEntity({
        url: "/Products/Product/Gets",
        parameters: {
            pageSize: 0,
            productStatus: 1
        }
    });
    var materials = Whale.Remote.GetEntity({
        url: "/Products/Material/Gets"
    });
    var processes = Whale.Remote.GetEntity({
        url: "/Products/Process/Gets"
    });
    var sizes = Whale.Remote.GetEntity({
        url: "/Products/Size/Gets"
    });
    function productEditor(container, options) {
        var selPro = $('<input required data-bind="value:' + options.field + '"/>')
            .appendTo(container)
            .kendoComboBox({
                autoBind: false,
                filter: "contains",
                dataTextField: "Module",
                dataValueField: "ID",
                dataSource: allProducts,
                change: function (e) {
                    if (selPro.dataItem() == null || selPro.dataItem() == undefined) {
                        $("#grid_orders").data("kendoGrid").cancelRow();
                        return;
                    }
                    var product = selPro.dataItem();
                    options.model.Product = product;

                    if (product.PType == 1) {
                        options.model.Material = { ID: 0, MaterialName: "" };
                        options.model.Process = { ID: 1, ProcessName: "无" };
                        options.model.Size = { ID: 0, SizeName: "无" };

                    } else {
                        options.model.Material = { ID: 0, MaterialName: "" };
                        options.model.Process = { ID: 0, ProcessName: "" };
                        options.model.Size = { ID: 0, SizeName: "" };
                    }


                    //#region 取最后一次交易的单价
                    //if ($("#txtCustomer").attr("data-value") > 0) {
                    //    var price = Whale.Remote.GetEntity({
                    //        url: "/Orders/DealOrder/GetLastPrice",
                    //        parameters: {
                    //            customerID: $("#txtCustomer").attr("data-value"),
                    //            productID: product.ID
                    //        }
                    //    });
                    //    if (price > 0)
                    //        options.model.UnitPrice = price;
                    //}
                    //#endregion

                    $("#grid_orders").data("kendoGrid").refresh();
                }
            }).data("kendoComboBox");
    }
    function materialEditor(container, options) {
        var selMaterial = $('<input data-bind="value:' + options.field + '"/>')
            .appendTo(container)
            .kendoDropDownList({
                dataTextField: "MaterialName",
                dataValueField: "ID",
                dataSource: {
                    transport: {
                        read: function (e) {
                            var ret = $.grep(materials, function (n, i) {
                                return n.MType == options.model.Product.PType;
                            });
                            e.success(ret);
                        }
                    }
                },
                dataBound: function (e) {
                    if (options.model.Material.ID == 0) {
                        options.model.Material = this.dataItem(0);
                    }
                }
            }).data("kendoDropDownList");
    }
    function processEditor(container, options) {
        var selProcess = $('<input data-bind="value:' + options.field + '"/>')
            .appendTo(container)
            .kendoDropDownList({
                dataTextField: "ProcessName",
                dataValueField: "ID",
                dataSource: {
                    transport: {
                        read: function (e) {
                            var ret;
                            if (options.model.Product.PType == 1) {
                                ret = $.grep(processes, function (n, i) {
                                    return n.ID == 1;
                                });
                            } else {
                                ret = $.grep(processes, function (n, i) {
                                    return n.ID > 1;
                                });
                            }
                            e.success(ret);
                        }
                    }
                },
                dataBound: function (e) {
                    if (options.model.Process.ID == 0) {
                        options.model.Process = this.dataItem(0);
                    }
                }
            }).data("kendoDropDownList");
    }
    function sizeEditor(container, options) {
        var selSize = $('<input data-bind="value:' + options.field + '"/>')
            .appendTo(container)
            .kendoDropDownList({
                dataTextField: "SizeName",
                dataValueField: "SizeName",
                dataSource: {
                    transport: {
                        read: function (e) {
                            var ret = $.grep(sizes, function (n, i) {
                                return n.PType == options.model.Product.PType;
                            });
                            e.success(ret);
                        }
                    }
                },
                //dataSource: {
                //    transport: {
                //        read: function (e) {
                //            var ret;
                //            if (options.model.Product.PType == 1) {
                //                ret = ["无"];
                //            } else {
                //                ret = ["0.25", "0.3", "0.35", "0.4", "0.45", "0.5", "0.6", "0.7", "0.8", "0.9", "1.0"]
                //            }
                //            e.success(ret);
                //        }
                //    }
                //},
                dataBound: function (e) {
                    if (options.model.Size.SizeName == "")
                        options.model.Size = this.dataItem(0);
                    else {

                    }
                }
            }).data("kendoDropDownList");
    }
    function quantityEditor(container, options) {
        var txtQuantity = $('<input data-bind="value:' + options.field + '"/>')
            .appendTo(container)
            .kendoNumericTextBox({
                decimals: 3,
                change: function (e) {
                    RefreshRow(options.model);
                }
            }).data("kendoNumericTextBox");
    }
    function priceEditor(container, options) {
        var txtPrice = $('<input data-bind="value:' + options.field + '"/>')
            .appendTo(container)
            .kendoNumericTextBox({
                format: "{0:c}",
                decimals: 5,
                change: function (e) {
                    RefreshRow(options.model);
                }
            }).data("kendoNumericTextBox");
    }
    function RefreshRow(model) {
        if (model != undefined && model.Product.ID > 0) {
            if (model.Quantity != "" && model.UnitPrice != "") {
                model.Money = model.Quantity * model.UnitPrice;
            }
            if (model.Product.PType == 2) {
                if (model.WeightQuantity != "" && model.WeightUnitPrice != "") {
                    model.Money = model.WeightQuantity * model.WeightUnitPrice;
                    if (model.Quantity != "") {
                        model.UnitPrice = model.Money / model.Quantity;
                    }
                }
            }
        }

        $("#grid_orders").data("kendoGrid").refresh();

        var sum = 0;
        $.each(orderDataSource.data(), function (i, o) {
            sum += o.Money;
        });
        $("#lblSum").html(kendo.toString(sum, "c"));
    }
</script>

<script class="grid_orders_dataSource">
    var orderDataSource = new kendo.data.DataSource({
        schema: {
            model: {
                fields: {
                    Product: { defaultValue: { ID: 0, ProductName: "", UnitName: "" } },
                    Material: { defaultValue: { ID: 0, MaterialName: "" } },
                    Process: { defaultValue: { ID: 0, ProcessName: "" } },
                    Size: { defaultValue: { ID: 0, SizeName: "" } },
                    Quantity: {},
                    UnitPrice: {},
                    WeightQuantity: {},
                    WeightUnitPrice: {},
                    Money: { editable: false, type: "number" }
                }
            }
        },
        change: function (e) {
            if (e.action == "remove") {
                RefreshRow();
            }
        }
    });
</script>

<script class="grid_orders_config">
    var hasSaved = false;
    $("#grid_orders").kendoGrid({
        columns: orderFields,
        pageable: false,
        toolbar: [{
            name: "create",
            text: "新增一行"
        }, {
            name: "save",
            text: "保存单据"
        }],
        editable: true,
        dataBound: function (e) {
            //让表头居中
            $("th.k-header").attr("style", "text-align:center; font-weight:bold;");
            $("a.k-grid-save-changes").attr("style", "font-weight:bold; float:right");
        },
        dataSource: orderDataSource,
        saveChanges: function (e) {
            if (hasSaved) return; else hasSaved = true;
            var values = {
                orderDate: kendo.toString($("#txtNoteDate").data("kendoDatePicker").value(), "yyyy-MM-dd"),
                customerID: $("#txtCustomer").attr("data-value"),
                method: "@ViewBag.Method",
                description: $("#txtDescription").val(),
                bookID: bookID,
                orderItems: []
            };
            values.orderItems = $.map(orderDataSource.data(), function (o) {
                return {
                    productID: o.Product.ID,
                    materialID: o.Material.ID,
                    processID: o.Process.ID,
                    size: o.Size.SizeName,
                    quantity: o.Quantity,
                    unitPrice: o.UnitPrice,
                    weightQuantity: o.WeightQuantity,
                    weightUnitPrice: o.WeightUnitPrice
                }
            });
            Whale.Remote.Operation({
                url: "/Orders/DealOrder/SaveOrders",
                parameters: values,
                success: function (result) {
                    location.href = "/Success/PrintDealOrder/" + result.OrderNo;
                },
                error: function (msg) {
                    hasSaved = false;
                    wndGeneralInformation.content(msg).open();
                }
            });
        }
    });
</script>


<script class="books">
    var bookOrdersFields = [{
        title: "单据号",
        field: "OrderNo",
        template: "#=GetOperations(OrderNo)#",
        width: 120
    }, {
        title: "客户",
        field: "Customer.ComplexName",
        attributes: { style: "text-align:left" },
        width: 300
    }, {
        title: "状态",
        field: "OrderStatus",
        template: "#=GetOrderStatusString(OrderStatus)#",
        width: 100
    }, {
        title: "日期",
        template: "#=kendo.toString(kendo.parseDate(NoteDate),'yyyy-MM-dd')#",
        width: 100
    }, {}];
    function GetOperations(orderNo) {
        var html = "<a href=\"javascript:LoadBookOrder('" + orderNo + "')\">" + orderNo + "</a>";
        return html;
    }

    var bookID;
    function LoadBookOrder(orderNo) {
        var bookOrder = Whale.Remote.GetEntity({
            url: "/Orders/DealOrder/LoadBookOrder",
            parameters: { orderNo: orderNo }
        });
        if (bookOrder != null) {
            bookID = bookOrder.AssociatedBookID;
            $("#txtCustomer").attr("data-value", bookOrder.CustomerID);
            $("#txtCustomer").data("kendoComboBox").text(bookOrder.Customer.ComplexName);
            
            $.each(bookOrder.Items, function (i, o) {
                o.Size = { ID: 0, SizeName: o.Size };
            });
            orderDataSource.data(bookOrder.Items);
            $("#grid_orders").data("kendoGrid").setDataSource(orderDataSource);
            $(".ld-tabs").data("kendoTabStrip").select(0);
        }
    }

    $(function () {
        $("#grid_books").kendoGrid({
            columns: bookOrdersFields,
            dataSource: Whale.dataSource({
                url: "/Orders/BookOrder/GetOrders",
                getParameters: function () {
                    return {
                        getCustomer: true,
                        orderStatus: "1,21",
                        orderMethod: 30 + parseInt("@ViewBag.Method")
                    };
                },
                pageSize: 20
            }),
            pageable: {
                messages: {
                    empty: "暂无数据"
                }
            },
            dataBound: function (e) {
                //让表头居中
                $("th.k-header").attr("style", "text-align:center; font-weight:bold;");
            }
        });
    });
</script>